//
//  YQAouthViewController.m
//  WeiboOC
//
//  Created by yang on 15/11/13.
//  Copyright © 2015年 yang. All rights reserved.
//

#import "YQAouthViewController.h"
@interface YQAouthViewController () <UIWebViewDelegate>
@property (nonatomic, strong) UIWebView* web;
@end
@implementation YQAouthViewController
- (void)loadView
{
    UIWebView* web = [[UIWebView alloc] init];
    web.delegate = self;
    self.web = web;
    self.view = web;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    [self loadAuothPage];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [SVProgressHUD dismiss];
}
- (void)setupUI
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStyleDone target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStyleDone target:self action:@selector(fullAccount)];
}
- (void)close
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)fullAccount
{
    NSString* str = @"document.getElementById('userId').value='542846574@qq.com',document.getElementById('passwd').value='yang910210'";
    [self.web stringByEvaluatingJavaScriptFromString:str];
}
- (void)loadAuothPage
{
    NSString* str = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", client_id, redirect_uri];
    NSURL* url = [NSURL URLWithString:str];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [self.web loadRequest:request];
}
//UIWebView的代理方法
- (void)webViewDidStartLoad:(UIWebView*)webView
{
    [SVProgressHUD show];
}
- (void)webViewDidFinishLoad:(UIWebView*)webView
{
    [SVProgressHUD dismiss];
}
//获取code
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    //   NSLog(@"%@", request);
    //判断request是否存在
    NSString* str = [request URL].absoluteString;
    if (str) {
        if ([str hasPrefix:@"https://api.weibo.com"]) {
            return YES;
        }
        if (![str hasPrefix:redirect_uri]) {

            return NO;
        }
    }
    NSString* query = [request URL].query;

    NSString* codeStr = @"code=";
    if (query) {
        NSString* code = [query substringFromIndex:codeStr.length];
        YQUserAccountViewModel *account = [[YQUserAccountViewModel alloc]init];
        [account loadAccessToken:code finished:^(NSError *error) {
            if (error != nil){
            [SVProgressHUD showInfoWithStatus:AppErrorTip];
                return ;
            }
            [self dismissViewControllerAnimated:NO completion:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:AppSwitchRootViewControler object:@"Welcome"];
            }];
        }];
    }
    return YES;
}
@end
